package Week5;

import java.util.*;

public class Day27 {
}

//牛客:kotori和气球
class Main7 {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        int n = in.nextInt() , m = in.nextInt();
        int ret = n;
        for(int i = 0; i < m - 1; i++){
            ret *= (n - 1);
            ret %= 109;
        }
        System.out.println(ret);
    }
}

//牛客:AB20 走迷宫
class Main8 {
    public static int N = 1010;
    public static int n , m ,x1 ,y1 ,x2 , y2;
    public static char[][] arr = new char[N][N];
    public static int[][] dist = new int[N][N];// 标记当前位置有没有搜索过，以及走到该位置时候的最短步数
    public static int[] dx = {0,0,1,-1};
    public static int[] dy = {1,-1,0,0};

    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        n = in.nextInt() ; m = in.nextInt();
        x1 = in.nextInt() ; y1 = in.nextInt();
        x2 = in.nextInt() ; y2 = in.nextInt();
        for(int i = 1; i <= n; i++){
            String s = in.next();
            for(int j = 1; j <= m; j++){
                arr[i][j] = s.charAt(j - 1);
            }
        }
        System.out.println(bfs());
    }

    public static int bfs(){
        if(arr[x2][y2] == '*') return -1;
        for(int i = 1; i <= n; i++){
            for(int j = 1; j <= m; j++){
                dist[i][j] = -1;
            }
        }

        Queue<int[]> q = new LinkedList<>();
        q.offer(new int[]{x1,y1});
        dist[x1][y1] = 0;
        while(!q.isEmpty()){
            int[] t = q.poll();
            int a = t[0] , b = t[1];
            for(int i = 0; i < 4; i++){
                int x = a + dx[i] , y = b + dy[i];
                if(x >= 1 && x <= n && y >= 1 && y <= m && dist[x][y] == -1 && arr[x][y] == '.'){
                    q.offer(new int[]{x,y});
                    dist[x][y] = dist[a][b] + 1;
                    if(x == x2 && y == y2){
                        return dist[x][y];
                    }
                }
            }
        }
        return -1;
    }
}

//牛客:NC147 主持人调度(二)
class Solution2 {
    /**
     * 代码中的类名、方法名、参数名已经指定，请勿修改，直接返回方法规定的值即可
     *
     * 计算成功举办活动需要多少名主持人
     * @param n int整型 有n个活动
     * @param startEnd int整型二维数组 startEnd[i][0]用于表示第i个活动的开始时间，startEnd[i][1]表示第i个活动的结束时间
     * @return int整型
     */
    public int minmumNumberOfHost (int n, int[][] startEnd) {
        // write code here
        //按第一个元素从小到大排序
        Arrays.sort(startEnd , (v1 , v2) ->{
            return v1[0] <= v2[0] ? -1 : 1;
        });

        //放入队列中
        PriorityQueue<Integer> q = new PriorityQueue<>();
        q.offer(startEnd[0][1]);

        for(int i = 1; i < n; i++){
            //判断是否重叠
            int a = startEnd[i][0] , b = startEnd[i][1];
            //不重叠，更新
            if(a >= q.peek()){
                q.poll();
                q.offer(b);
            }else{
                //重叠添加新的个数
                q.offer(b);
            }
        }
        return q.size();
    }
}